import * as auth from '../../utils/auth'
import { login, getUserInfo, getUserDetailById } from '../../api/user'
// 重置路由
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: auth.getToken() || null,
    userInfo: {}
  },
  mutations: {
    // 设置用户token
    setToken (state, token) {
      state.token = token
      auth.setToken(token)
    },
    delToken (state) {
      state.token = null
      auth.removeToken()
    },
    // 设置用户信息
    setUserInfo (state, userInfo) {
      state.userInfo = userInfo
    },
    delUsreInfo (state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 退出登录 (删除token,用户信息,和动态添加的路由)
    async logOut ({ commit }) {
      commit('delToken')
      commit('delUsreInfo')
      // 重置路由
      resetRouter()
      commit('routes/setRouteLiset', [], { root: true })
    },
    // 获取用户信息  在前置守卫中调用
    async getUserInfoActions ({ commit }) {
      const res = await getUserInfo()
      const photo = await getUserDetailById(res.userId)
      commit('setUserInfo', { ...res, ...photo })
      // console.log({ ...res, ...photo })
      return res.roles
    },
    // async getPhoto ({ commit }) {
    //   console.log(photo)
    // },
    // 获取用户token
    async getToken ({ commit }, formDate) {
      const token = await login(formDate)
      commit('setToken', token)
    }
  }
}

